'''
Distributed under the MIT License(MIT)

Copyright(c) 2023 Jihua Zou EMail: ghuazo@qq.com QQ:137336521

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files(the "Software"), to deal in the
Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and /or sell copies
of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions :

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import http.client
import json
import random
import time


class ApolloClient:
    def __init__(self,host,port):
        self.host = host
        self.port = port
        self.timeout = 60

    def get_contract(self)->dict:
        try:
            conn = http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
            # 发送 GET 请求
            conn.request("GET", "/get_contract")
            # 获取响应
            response = conn.getresponse()
            # 读取响应内容
            response_data = response.read()
            print(f"Status: {response.status} {response.reason} Response:{response_data.decode("utf-8")}")
            result = json.loads(response_data)
            return result
        except Exception as e:
            print("Error:", e)

        finally:
            # 关闭连接
            conn.close()
        return None
    
    def get_runinfo(self,code:str)->dict:
        try:
            conn = http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
            # 发送 GET 请求
            conn.request("GET", "/get_runinfo?code="+code)
            # 获取响应
            response = conn.getresponse()
            # 读取响应内容
            response_data = response.read()
            print(f"Status: {response.status} {response.reason} Response:{response_data.decode("utf-8")}")
            result = json.loads(response_data)
            return result[code]
        except Exception as e:
            print("Error:", e)

        finally:
            # 关闭连接
            conn.close()
        return None

    def sync_position(self,code:str,ratio:float,force:bool=False)->bool:
        # 请求头和 POST 数据
        head_data = {"Content-Type": "application/json"}
        req_data = json.dumps({
            "code": code,
            "ratio": ratio,
            "force": force
        })

        try:
            conn = http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
            # 发送 POST 请求
            conn.request("POST", "/sync_target", body=req_data, headers=head_data)
            # 获取响应
            response = conn.getresponse()
            # 读取响应内容
            response_data = response.read()
            print(f"Status: {response.status} {response.reason} Response:{ response_data.decode("utf-8")}")
            result = json.loads(response_data)
            return result["result"] == "Success"
        except Exception as e:
            print("Error:", e)
        finally:
            # 关闭连接
            conn.close()
        return False

    def sync_attribute(self,code:str,attribute:dict)->bool:
        # 请求头和 POST 数据
        head_data = {"Content-Type": "application/json"}
        req_json = {"code": code}
        if "min_price" in attribute :
            req_json['min_price'] = attribute["min_price"]
        if "max_price" in attribute :
            req_json['max_price'] = attribute["max_price"]
        if "trand_slope" in attribute :
            req_json['trand_slope'] = attribute["trand_slope"]
        if "grid_base" in attribute :
            req_json['grid_base'] = attribute["grid_base"]
        if "grid_density" in attribute :
            req_json['grid_density'] = attribute["grid_density"]
        if "grid_size" in attribute :
            req_json['grid_size'] = attribute["grid_size"]
        if "use_grid" in attribute :
            req_json['use_grid'] = attribute["use_grid"]
            
        req_data = json.dumps(req_json)
        print(req_data)
        try:
            conn = http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
            # 发送 POST 请求
            conn.request("POST", "/sync_attribute", body=req_data, headers=head_data)
            # 获取响应
            response = conn.getresponse()
            # 读取响应内容
            response_data = response.read()
            print(f"Status: {response.status} {response.reason} Response:{ response_data.decode("utf-8")}")
            result = json.loads(response_data)
            return result["result"] == "Success"
        except Exception as e:
            print("Error:", e)
        finally:
            # 关闭连接
            conn.close()
        return False



if __name__ == "__main__":

    client = ApolloClient('127.0.0.1',19527)
    #随机调仓
    while(True):
        #随机生成一个持仓系数
        ratio = (random.random() * 2) - 1 
        client.sync_position("SHFE.ag2506",ratio)
        time.sleep(1)
        position = client.get_runinfo("SHFE.ag2506")
        print(position)